import server from "./server.js";

function myserver() {
  this.server = server;
  this.nowHandle = null;
}
// 调用：server.setVue(this).centerPanel.getCenterPanel()
myserver.prototype.setVue = function (vueObj) {
  this.nowHandle = vueObj;
  return this;
};
/**
 * @description: 解析路由
 * @param {string} name
 * @param {object} urlOb
 */
myserver.prototype.parseRouter = function (name, urlObj) {
  let ob = (this[name] = {});
  Object.keys(urlObj).forEach(apiName => {
    ob[apiName] = this.sendMsg.bind(name, apiName, urlObj[apiName]);
    ob[apiName].state = "ready"; // 防止重复提交
  });
};
// 造库原则：再给予别人便利操作的同时，也给予他自定义的空间（config）
myserver.prototype.sendMsg = function (moduleName, apiName, config) {
  let config = config || {};
  let url = config.url;
  let type = config.type || "get";
  let data = config.data || {};
  let bindName = config.bindName || apiName;
  // 请求处理前-请求处理-请求处理后
  let before = () => {
    this[moduleName][apiName].state = "ready";
  };
  let defaultFn = res => {
    if (this.nowHandle) this.nowHandle[bindName] = res.data; // 默认自动化绑定
  };
  let success = config.success || defaultFn;
  if (this[moduleName][apiName].state === "ready") {
    this.server[type](url, data).then(before).then(success);
    this[moduleName][apiName].state = "wait";
  }
};
export default new myserver();
